package me.fung.wubi.app.component.swing

import javax.swing.JFileChooser
import javax.swing.filechooser.FileFilter
import javax.swing.filechooser.FileNameExtensionFilter

fun chooseFile(file: String?, fileSelectionModel: Int = JFileChooser.FILES_ONLY): String? {
    val chooser = JFileChooser(file ?: ".resources").apply {
        this.fileSelectionMode = fileSelectionModel
        addChoosableFileFilter(FileNameExtensionFilter("文本文件 *.txt *.dic", "txt", "dic"))
    }
    val state = chooser.showOpenDialog(null)
    if (state != JFileChooser.APPROVE_OPTION) return null
    return chooser.selectedFile?.absoluteFile?.absolutePath
}


val textFileFilter = FileNameExtensionFilter("文本文件 *.txt *.dic", "txt", "dic")
fun saveFileDialog(
    file: String?,
    filterMap: Map<FileFilter, String> = mapOf(textFileFilter to ".txt"),
    fileSelectionModel: Int = JFileChooser.FILES_ONLY,
): String? {
    val chooser = JFileChooser(file ?: ".resources").apply {
        this.fileSelectionMode = fileSelectionModel
        filterMap.forEach { (filter, _) ->
            addChoosableFileFilter(filter)
        }
    }
    val state = chooser.showSaveDialog(null)
    if (state != JFileChooser.APPROVE_OPTION) return null
    val chooseFilter = chooser.fileFilter
    val extName = filterMap.getOrElse(chooseFilter) { "" }
    return chooser.selectedFile?.absoluteFile?.absolutePath + extName
}

